<template>
  <div class="tree">
    <div class="main item">
      <el-checkbox  @change="checkedChange" v-model="data.Checked">
      <span class="menuName">{{ data.MenuName }}</span>
      </el-checkbox>
    </div>
    <div v-if="data.Children.length != 0" class="children">
      <AppMenuPermissionTree @menu-checked="childMenuChecked" :data="child" v-for="child in data.Children" :key="child.Id"></AppMenuPermissionTree>
    </div>
    <div v-else class="buttons item">
    <span style="font-size:12px;margin-right:5px;color:#c8c9cc" v-if="data.Buttons.length == 0" >暂无按钮</span>
      <el-checkbox v-model="btn.Checked"   v-for="(btn,index) in data.Buttons" :key="index">{{ btn.ButtonName }}</el-checkbox>
    </div>
  </div>
</template>

<script >
import { defineComponent } from "vue"
export default defineComponent({
  props: {
    data: {
      type: Object,
    }
  },
  name: "AppMenuPermissionTree",
  data() {
    return {

    }
  },
  methods: {
      checkedChange(checked){
        if(checked){
          //  菜单选中时 父级菜单也要选中
          this.$emit("menu-checked",this.data);
        }

        this.checkMenu(this.data,checked);
      },
      // 修改菜单时候 对菜单子级和按钮统一修改
      checkMenu(menu,checked){
        menu.Checked = checked;

  
        // 把所有按钮修改状态
        for(let btn of menu.Buttons){
          btn.Checked = checked;
        }
        // 递归
        for(let child of menu.Children){
          this.checkMenu(child,checked)
        }
      },
      childMenuChecked(child){
        let existChild = this.data.Children.find(t=>t.Id == child.Id);
        if(existChild){
          // 子菜单选中的时候父级也选中
          this.data.Checked = true;
          // 向上传递事件
          this.$emit("menu-checked",this.data);
        }
      }
  },
  created() {

  }
})
</script>

<style lang='scss' scoped>
.tree {
  display: flex;
  width:100%;
  .menuName{
    font-weight: bold;
  }
  .item {
    border: 1px solid #e4e7ed;
    padding: 15px;
    width:100%;
  }
  .main{
    max-width: 150px;
  }
  .children{
    width:100%;
  }
  .button{
    width:100%;
  }
}
</style>